import os
import datetime
import subprocess
import tempfile

from django.core.mail import EmailMessage
from django.conf import settings
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Backup database and send via email'

    def handle(self, *args, **options):
        # 生成备份文件名
        now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        backup_dir = os.path.join(settings.BASE_DIR, 'ctbloge/uploads/backups')
        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)
        backup_file = os.path.join(backup_dir, f'backup_{now}.sql')

        # 获取数据库配置
        db = settings.DATABASES['default']
        db_name = db['NAME']
        db_user = db['USER']
        db_password = db['PASSWORD']
        db_host = db['HOST'] or 'localhost'
        db_port = db['PORT'] or '3306'

        try:
            # 创建临时配置文件存储敏感信息
            with tempfile.NamedTemporaryFile(mode='w', delete=False) as cfg_file:
                cfg_content = f"""[client]
            user={db_user}
            password={db_password}
            host={db_host}
            port={db_port}
            """
                cfg_file.write(cfg_content)
                cfg_path = cfg_file.name
            # 执行备份命令
            # cmd = (
            #     f"mysqldump --user={db_user} "
            #     f"--defaults-extra-file=\"{cfg_path}\" "  # 使用配置文件认证
            #     f"{db_name} > {backup_file}"
            # )
            # 修改cmd命令为：
            cmd = (
                f"\"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump\" "  # 注意双引号包裹路径
                f"--defaults-extra-file=\"{cfg_path}\" "  # 使用配置文件认证
                f"{db_name} > \"{backup_file}\""  # 路径含空格需加双引号
            )

            subprocess.run(cmd, shell=True, check=True)
            self.stdout.write(self.style.SUCCESS('数据库备份成功'))
        except subprocess.CalledProcessError as e:
            self.stderr.write(self.style.ERROR(f'备份失败: {e}'))
            return

        try:
            # 发送邮件
            subject = f"数据库备份 {now}"
            body = "请查收最新的数据库备份文件"
            email = EmailMessage(
                subject,
                body,
                settings.EMAIL_HOST_USER,  # 发件人
                [settings.EMAIL_HOST_USER]     # 收件人
            )
            email.attach_file(backup_file)
            email.send()
            self.stdout.write(self.style.SUCCESS('邮件发送成功'))
        except Exception as e:
            self.stderr.write(self.style.ERROR(f'邮件发送失败: {e}'))
        finally:
            # 删除临时配置文件
            if os.path.exists(cfg_path):
                os.unlink(cfg_path)